package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.query.impl.EmployeeQuery;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    EmployeeMapper employeeMapper;


    public void saveOrUpdate(Employee record) {
        if (record.getId() == null) {
            if (record.getPassword() != null) {
                record.getPassword();
                Md5Hash md5Hash = new Md5Hash(record.getPassword(), record.getUsername(), 2);
                record.setPassword(md5Hash.toString());
            }
            record.setState(true);
            employeeMapper.insert(record);
            List<Role> roles = record.getRoles();
            for (Role role : roles) {
                employeeMapper.insertRelation(record.getId(), role.getId());
            }
        } else {
            employeeMapper.updateByPrimaryKey(record);

            //删除关系
            employeeMapper.deleteRelation(record.getId());
            //关联关系
            List<Role> roles = record.getRoles();
            for (Role role : roles) {
                employeeMapper.insertRelation(record.getId(), role.getId());
            }
        }
    }

    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    public Employee getByUsername(String name) {
        return employeeMapper.getByUsername(name);
    }


    public PageResult query(EmployeeQuery qo) {
        int rows = employeeMapper.queryForCount(qo);
        if (rows == 0) {
            new PageResult(rows, Collections.EMPTY_LIST);
        }
        List<Employee> result = employeeMapper.queryForList(qo);
        return new PageResult(rows, result);
    }

    public void changeState(Long id) {
        employeeMapper.changeState(id);
    }

    public void rsetPassword(Long id, String s) {
        employeeMapper.rsetPassword(id, s);
    }

    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }

    public List<Long> getRoleIdByEmployeeId(Long id){return employeeMapper.getRoleIdByEmployeeId(id);}

}
